import axios from 'axios'
import { errorDeal, getStore, globalLoading, setStore, successDeal } from '@/utils/utils'
import JsBridge from '@/utils/JsBridge.js'
import { showLoadingToast, closeToast, showToast } from 'vant';
import store from '@/store';

let isAndroid = navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Adr') > -1;
let isiOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);

axios.interceptors.request.use(function (config) {
  return config;
}, function (error) {

  return Promise.reject(error);
});

axios.interceptors.response.use(function (response) {
  return response;
}, function (error) {
  if (!error.response) {
    store.state.noNetwork = true
    throw new Error('当前无网络，请检查您的网络是否可用')
  }
  return Promise.reject(error);
});

/**
 * 
 * 获取鉴权信息
 */
export const getAuth = () => {
  return new Promise((resolve, reject) => {
    let userInfo = getStore('USER_INFO')

    let json = {
      "timestamp": new Date().getTime(),
      "tmsi": userInfo.tmsi || '',
      "userId": userInfo.userId || '',
    }
    JsBridge.callHandler('getAuthInfo', json, (response) => {
      let boryaAuth = ""
      try {
        boryaAuth = JSON.parse(response).data
        boryaAuth.timestamp = json.timestamp
        boryaAuth.userId = json.userId
        resolve(boryaAuth)
      } catch (err) {
        console.log('getAuth失败返回:', err)
        showToast(err.message)
      }
    })
  })
}

/**
 * 获取接口地址
 */
export const getDomain = () => {
  return new Promise((resolve, reject) => {
    if (!isAndroid && !isiOS) {
      resolve(false)
    } else {
      JsBridge.callHandler('getDomain', {}, (response) => {
        let domain = JSON.parse(response).data.domain
        resolve(domain)
      })
    }
  })
}


/**
 *@describe http请求
 *@method {String} 请求方式
 *@url {String} 接口地址
 *@params {Object} 对应接口参数
 **/
export default async function _http(method = 'post', { url, apiName, storeName }, params = {}, loading = true, headers = {}) {
  console.log(store.state.noNetwork)
  if (loading && !store.state.noNetwork) {
    showLoadingToast({
      message: '请求中...',
      forbidClick: true,
      duration: 0,
    });
  }

  let boryaAuth = {}
  let Authorization = {}
  let json = {}
  let body = {}

  if (isAndroid || isiOS) {
    boryaAuth = await getAuth()
    if (boryaAuth && !params.noAuthorization) {
      Authorization = { Authorization: boryaAuth.authString }
      json = {
        Token: boryaAuth.token,
        platformHeadType: 'COMPANY_APP',
        userId: boryaAuth.userId,
        timestamp: boryaAuth.timestamp,
      }
    }
  } else {
    let userInfo = getStore('USER_INFO')

    if (userInfo && !params.noAuthorization) {
      Authorization = { Authorization: `${userInfo.userId},'','',3,20,''` }
      json = {
        Token: `Bearer ${userInfo.token}`,
        platformHeadType: 'COMPANY_APP',
      }
    } else {
      // Authorization = { Authorization: `'','','',3,20,''` }
    }
    body = {}
  }
  let domain = await getDomain()
  return axios({
    method: method,
    url: `${domain ? String(domain) : ''}${url}`,
    // url: '' + url,

    headers: Object.assign({
      'Content-Type': params.contentType ? 'multipart/form-data; boundary=----WebKitFormBoundarynl6gT1BKdPWIejNq' : 'application/json;charset=UTF-8;'
    }, json, boryaAuth ? Authorization : '', headers, { resourceVersion: RESOURCE_VERSION }),
    params: method === 'get' ? params : '' || method === 'delete' ? params : '',
    data: Object.assign(params, body),
    // data: typeof params === 'object' ? JSON.stringify(params) : params,
    timeout: 1000 * 30,
    responseType: params.responseType == 'blob' ? 'blob' : undefined,
    withCredentials: true
  }).then(res => {
    store.state.noNetwork = false
    if (loading) {
      closeToast()
    }
    // 数据流，直接返回
    if (params.responseType == 'blob') {
      return res
    }

    if (res && res.data && res.data.code == 200) {
      if (storeName) {
        // 设置无网环境下展示内容
        setStore(storeName, res.data.data)
      }
      return res.data
    } else throw res.data
  }).catch(error => {
    if (loading) {
      closeToast()
    }
    errorDeal(error)
    throw error
  })
}
